<template>
  <div class="background-color-picker">
    <!-- 颜色类型选择 -->
    <div class="color-type-selector">
      <el-radio-group v-model="colorType" @change="handleColorTypeChange">
        <el-radio-button label="solid">纯色</el-radio-button>
        <el-radio-button label="gradient">渐变色</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 纯色选择器 -->
    <div v-if="colorType === 'solid'" class="solid-color-picker">
      <el-color-picker
        v-model="solidColor"
        @change="handleSolidColorChange"
        show-alpha
        size="small"
      />
      <el-input
        v-model="solidColor"
        size="small"
        placeholder="#ffffff"
        @blur="handleSolidColorInput"
        style="margin-left: 8px; width: 120px;"
      />
    </div>

    <!-- 渐变色选择器 -->
    <div v-if="colorType === 'gradient'" class="gradient-color-picker">
      <!-- 渐变方向选择 -->
      <div class="gradient-direction">
        <label>方向：</label>
        <el-select v-model="gradientDirection" size="small" @change="updateGradient">
          <el-option label="水平" value="to right"></el-option>
          <el-option label="垂直" value="to bottom"></el-option>
          <el-option label="对角线" value="135deg"></el-option>
          <el-option label="径向" value="circle"></el-option>
        </el-select>
      </div>

      <!-- 渐变颜色点 -->
      <div class="gradient-stops">
        <div
          v-for="(stop, index) in gradientStops"
          :key="index"
          class="gradient-stop"
        >
          <el-color-picker
            v-model="stop.color"
            @change="updateGradient"
            size="small"
          />
          <el-input-number
            v-model="stop.position"
            :min="0"
            :max="100"
            size="small"
            @change="updateGradient"
          />
          <span>%</span>
          <el-button
            v-if="gradientStops.length > 2"
            type="text"
            size="mini"
            icon="el-icon-delete"
            @click="removeGradientStop(index)"
          />
        </div>
        <el-button
          v-if="gradientStops.length < 5"
          type="text"
          size="small"
          icon="el-icon-plus"
          @click="addGradientStop"
        >
          添加颜色点
        </el-button>
      </div>

      <!-- 预设渐变色模板 -->
      <div class="gradient-presets">
        <label>预设模板：</label>
        <div class="preset-grid">
          <div
            v-for="preset in gradientPresets"
            :key="preset.name"
            class="preset-item"
            :style="{ background: preset.value }"
            @click="applyPreset(preset)"
            :title="preset.name"
          />
        </div>
      </div>

      <!-- 渐变预览 -->
      <div class="gradient-preview">
        <label>预览：</label>
        <div
          class="preview-box"
          :style="{ background: currentGradient }"
        />
        <el-input
          v-model="currentGradient"
          size="small"
          readonly
          style="margin-left: 8px; width: 200px;"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BackgroundColorPicker',
  props: {
    value: {
      type: String,
      default: '#409eff'
    }
  },
  data() {
    return {
      colorType: 'solid',
      solidColor: '#409eff',
      gradientDirection: '135deg',
      gradientStops: [
        { color: '#667eea', position: 0 },
        { color: '#764ba2', position: 100 }
      ],
      currentGradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      gradientPresets: [
        { name: '蓝紫渐变', value: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' },
        { name: '粉红渐变', value: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)' },
        { name: '蓝青渐变', value: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)' },
        { name: '橙红渐变', value: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)' },
        { name: '绿青渐变', value: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)' },
        { name: '紫粉渐变', value: 'linear-gradient(135deg, #d299c2 0%, #fef9d7 100%)' },
        { name: '蓝绿渐变', value: 'linear-gradient(135deg, #89f7fe 0%, #66a6ff 100%)' },
        { name: '红橙渐变', value: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)' },
        { name: '黄绿渐变', value: 'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)' },
        { name: '紫蓝渐变', value: 'linear-gradient(135deg, #a8c0ff 0%, #3f2b96 100%)' },
        { name: '水平蓝紫', value: 'linear-gradient(to right, #667eea 0%, #764ba2 100%)' },
        { name: '垂直粉红', value: 'linear-gradient(to bottom, #f093fb 0%, #f5576c 100%)' }
      ]
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        this.parseValue(newVal)
      }
    }
  },
  methods: {
    // 解析传入的颜色值
    parseValue(value) {
      if (!value) return
      
      if (value.includes('gradient')) {
        this.colorType = 'gradient'
        this.parseGradient(value)
      } else {
        this.colorType = 'solid'
        this.solidColor = value
      }
    },

    // 解析渐变色
    parseGradient(gradientStr) {
      try {
        // 简单的渐变色解析，支持常见的格式
        const matches = gradientStr.match(/linear-gradient\(([^)]+)\)/)
        if (matches) {
          const params = matches[1]
          
          // 解析方向
          if (params.includes('to right')) {
            this.gradientDirection = 'to right'
          } else if (params.includes('to bottom')) {
            this.gradientDirection = 'to bottom'
          } else if (params.includes('circle')) {
            this.gradientDirection = 'circle'
          } else {
            const degMatch = params.match(/(\d+)deg/)
            if (degMatch) {
              this.gradientDirection = degMatch[1] + 'deg'
            }
          }
          
          // 解析颜色点
          const colorMatches = params.match(/#[a-fA-F0-9]{6}\s+\d+%|#[a-fA-F0-9]{6}\s+0/g)
          if (colorMatches) {
            this.gradientStops = colorMatches.map(match => {
              const parts = match.trim().split(' ')
              return {
                color: parts[0],
                position: parseInt(parts[1]) || 0
              }
            })
          }
        }
      } catch (e) {
        console.warn('解析渐变色失败:', e)
      }
    },

    // 颜色类型变化
    handleColorTypeChange(type) {
      if (type === 'solid') {
        this.emitValue(this.solidColor)
      } else {
        this.updateGradient()
      }
    },

    // 纯色变化
    handleSolidColorChange(color) {
      this.solidColor = color
      this.emitValue(color)
    },

    // 纯色输入框变化
    handleSolidColorInput() {
      this.emitValue(this.solidColor)
    },

    // 更新渐变色
    updateGradient() {
      const stops = this.gradientStops
        .sort((a, b) => a.position - b.position)
        .map(stop => `${stop.color} ${stop.position}%`)
        .join(', ')
      
      if (this.gradientDirection === 'circle') {
        this.currentGradient = `radial-gradient(circle, ${stops})`
      } else {
        this.currentGradient = `linear-gradient(${this.gradientDirection}, ${stops})`
      }
      
      this.emitValue(this.currentGradient)
    },

    // 添加渐变颜色点
    addGradientStop() {
      if (this.gradientStops.length < 5) {
        const newPosition = Math.min(100, this.gradientStops[this.gradientStops.length - 1].position + 20)
        this.gradientStops.push({
          color: '#ffffff',
          position: newPosition
        })
        this.updateGradient()
      }
    },

    // 删除渐变颜色点
    removeGradientStop(index) {
      if (this.gradientStops.length > 2) {
        this.gradientStops.splice(index, 1)
        this.updateGradient()
      }
    },

    // 应用预设模板
    applyPreset(preset) {
      this.parseGradient(preset.value)
      this.updateGradient()
    },

    // 发送值变化事件
    emitValue(value) {
      this.$emit('input', value)
      this.$emit('change', value)
    }
  }
}
</script>

<style scoped>
.background-color-picker {
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
}

.color-type-selector {
  margin-bottom: 16px;
}

.solid-color-picker {
  display: flex;
  align-items: center;
}

.gradient-color-picker > * {
  margin-bottom: 12px;
}

.gradient-color-picker > *:last-child {
  margin-bottom: 0;
}

.gradient-direction {
  margin-bottom: 12px;
}

.gradient-direction label {
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
}

.gradient-stops {
  margin-bottom: 12px;
}

.gradient-stop {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  gap: 8px;
}

.gradient-stop span {
  font-size: 12px;
  color: #909399;
}

.gradient-presets {
  margin-bottom: 12px;
}

.gradient-presets label {
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
}

.preset-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 8px;
  margin-top: 8px;
}

.preset-item {
  width: 30px;
  height: 30px;
  border-radius: 4px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color 0.3s;
}

.preset-item:hover {
  border-color: #409eff;
}

.gradient-preview {
  display: flex;
  align-items: center;
}

.gradient-preview label {
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
}

.preview-box {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}
</style>
